package com.yunsc.content.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunsc.common.exception.YunscException;
import com.yunsc.common.utils.PageResult;
import com.yunsc.content.dao.YunscArticleDao;
import com.yunsc.content.dto.ArticleDTO;
import com.yunsc.content.dto.QueryArticleDTO;
import com.yunsc.content.entity.YunscArticleEntity;
import com.yunsc.content.service.YunscArticleService;
import com.yunsc.media.service.YunscUploadFileService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


@Service("yunscArticleService")
public class YunscArticleServiceImpl extends ServiceImpl<YunscArticleDao, YunscArticleEntity> implements YunscArticleService {

    @Resource
    private YunscUploadFileService uploadFileService;

    @Override
    public void addArticle(ArticleDTO param, Integer storeId) {
        YunscArticleEntity article = new YunscArticleEntity();
        BeanUtils.copyProperties(param.getForm(), article);
        article.setStoreId(storeId);
        this.save(article);
    }

    @Override
    public PageResult<YunscArticleEntity> articleList(QueryArticleDTO param, Integer storeId) {
        Page<YunscArticleEntity> pageResult =  this.baseMapper.selectArticlePage(new Page<>(param.getPage(), param.getPageSize()), param, storeId);
        pageResult.getRecords().forEach(article -> {
            article.setImageUrl(uploadFileService.queryFileUrlById(article.getImageId()));
        });
        return PageResult.formatPageResult(pageResult.getRecords(), param.getPage(), param.getPageSize(), pageResult.getTotal());
    }

    @Override
    public void deleteArticle(Integer articleId) {
        this.update().set("is_delete", 1).eq("article_id", articleId).update();
    }

    @Override
    public void updateArticle(ArticleDTO param) {
        Integer articleId = param.getArticleId();
        YunscArticleEntity article = this.getById(articleId);
        if (article == null) {
            throw new YunscException("文章不存在");
        }
        BeanUtils.copyProperties(param.getForm(), article);
        article.setArticleId(articleId);

        this.updateById(article);
    }
}